package com.uzai.console.service.alarm.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.enums.MerConfigTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.alarm.alarmevent.AlarmEventConfigDto;
import com.uzai.console.dto.alarm.alarmevent.AlarmEventTypeDto;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.entity.Merchant;
import com.uzai.console.enums.SmsType;
import com.uzai.console.mapper.MerBaseConfigMapper;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.service.alarm.AlarmEventService;
import com.uzai.console.vo.alarm.alarmevent.AlarmEventConfigVo;
import com.uzai.console.vo.alarm.alarmevent.AlarmEventTypeVo;
import com.uzai.console.vo.smscode.SmsCodeVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 报警规则
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class AlarmEventServiceImpl implements AlarmEventService {

    Logger logger = LoggerFactory.getLogger(AlarmEventServiceImpl.class);

    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 查询事件监控详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public AlarmEventConfigVo findAlarmEventConfig(Long merId){
        AlarmEventConfigVo alarmEventConfigVo = new AlarmEventConfigVo();
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.ALARM_EVENT_CONFIG.getValue());
        if(merBaseConfig != null){
            alarmEventConfigVo = JSONObject.parseObject(merBaseConfig.getVal(), AlarmEventConfigVo.class);
        }
        return alarmEventConfigVo;
    }

    /**
     * 修改事件监控
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alarmEventConfigDto
     * @return null
     */
    public void updateAlarmEventConfig(Long merId, AlarmEventConfigDto alarmEventConfigDto){

        if(alarmEventConfigDto == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "事件监控配置不能为空");
        }

        Merchant merchant = merchantMapper.selectById(merId);
        if(merchant == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该运营商");
        }

        //查询运营商短信验证功能信息
        boolean smsCodeFlag = true;
        MerBaseConfig merBaseConfig_smsCode = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.SMS_CODE_CONFIG.getValue());
        if (merBaseConfig_smsCode != null) {
            SmsCodeVo smsCodeVo = JSONObject.parseObject(merBaseConfig_smsCode.getVal(), SmsCodeVo.class);
            if(smsCodeVo != null && smsCodeVo.getAlarmEventSave() == 0){ //不需要认证
                smsCodeFlag = false;
            }
        }

        if(smsCodeFlag){
            //如果输入的验证码不是系统通用密码，则需要验证
            if(!uzaiConsoleSysConfig.getDefaultPassword().equals(alarmEventConfigDto.getCode())){
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.ALARM_EVENT_UPDATE.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(alarmEventConfigDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(alarmEventConfigDto.getCode())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.ALARM_EVENT_UPDATE.getDesc(), merchant.getMobile()));
            }
        }

        //查询当前的配置
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.ALARM_EVENT_CONFIG.getValue());
        Integer now = DateUtil.getNowTime();
        //如果存在则修改
        if(merBaseConfig != null){//修改
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(alarmEventConfigDto)));
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.update(merBaseConfig);
        }else{ //不存在就添加
            merBaseConfig = new MerBaseConfig();
            merBaseConfig.setId(IdWorker.getId());
            merBaseConfig.setMerId(merId);
            merBaseConfig.setType(MerConfigTypeEnum.PRODUCTS.getValue());
            merBaseConfig.setKey(MerConfigKeyEnum.ALARM_EVENT_CONFIG.getValue());
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(alarmEventConfigDto)));
            merBaseConfig.setCreateTime(now);
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.insert(merBaseConfig);
        }

        //更新reids缓存
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.ALARM_EVENT_CONFIG.getKey(), merId), merBaseConfig.getVal());

    }

    /**
     * 查询事件监控报警通道详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public AlarmEventTypeVo findAlarmEventType(Long merId){
        AlarmEventTypeVo alarmEventTypeVo = new AlarmEventTypeVo();
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.ALARM_EVENT_TYPE.getValue());
        if(merBaseConfig != null){
            alarmEventTypeVo = JSONObject.parseObject(merBaseConfig.getVal(), AlarmEventTypeVo.class);
        }
        return alarmEventTypeVo;
    }

    /**
     * 修改事件监控报警通道
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param alarmEventTypeDto
     * @return null
     */
    public void updateAlarmEventType(Long merId, AlarmEventTypeDto alarmEventTypeDto){

        if(alarmEventTypeDto == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "事件监控报警渠道不能为空");
        }

        //查询当前的配置
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.ALARM_EVENT_TYPE.getValue());
        Integer now = DateUtil.getNowTime();
        //如果存在则修改
        if(merBaseConfig != null){//修改
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(alarmEventTypeDto)));
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.update(merBaseConfig);
        }else{ //不存在就添加
            merBaseConfig = new MerBaseConfig();
            merBaseConfig.setId(IdWorker.getId());
            merBaseConfig.setMerId(merId);
            merBaseConfig.setType(MerConfigTypeEnum.PRODUCTS.getValue());
            merBaseConfig.setKey(MerConfigKeyEnum.ALARM_EVENT_TYPE.getValue());
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(alarmEventTypeDto)));
            merBaseConfig.setCreateTime(now);
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.insert(merBaseConfig);
        }
    }
}
